import subprocess
import os
from typing import Dict, Optional, Tuple
from config_manager import GitAccount

class GitManager:
    def __init__(self):
        pass
    
    def get_current_config(self) -> Dict[str, str]:
        config = {}
        try:
            result = subprocess.run(['git', 'config', '--global', '--list'], 
                                  capture_output=True, text=True, check=True)
            for line in result.stdout.strip().split('\n'):
                if '=' in line:
                    key, value = line.split('=', 1)
                    config[key] = value
        except subprocess.CalledProcessError:
            pass
        return config
    
    def get_current_user_info(self) -> Tuple[Optional[str], Optional[str]]:
        try:
            name_result = subprocess.run(['git', 'config', '--global', 'user.name'], 
                                       capture_output=True, text=True, check=True)
            email_result = subprocess.run(['git', 'config', '--global', 'user.email'], 
                                        capture_output=True, text=True, check=True)
            return name_result.stdout.strip(), email_result.stdout.strip()
        except subprocess.CalledProcessError:
            return None, None
    
    def set_global_config(self, account: GitAccount) -> bool:
        try:
            subprocess.run(['git', 'config', '--global', 'user.name', account.username], 
                          check=True)
            subprocess.run(['git', 'config', '--global', 'user.email', account.email], 
                          check=True)
            return True
        except subprocess.CalledProcessError as e:
            print(f"设置Git配置失败: {e}")
            return False
    
    def set_local_config(self, account: GitAccount, repo_path: str = ".") -> bool:
        try:
            original_cwd = os.getcwd()
            os.chdir(repo_path)
            
            subprocess.run(['git', 'config', 'user.name', account.username], check=True)
            subprocess.run(['git', 'config', 'user.email', account.email], check=True)
            
            os.chdir(original_cwd)
            return True
        except (subprocess.CalledProcessError, OSError) as e:
            print(f"设置本地Git配置失败: {e}")
            return False
    
    def backup_config(self, backup_file: str = "git_config_backup.txt") -> bool:
        try:
            config = self.get_current_config()
            with open(backup_file, 'w', encoding='utf-8') as f:
                for key, value in config.items():
                    f.write(f"{key}={value}\n")
            return True
        except Exception as e:
            print(f"备份配置失败: {e}")
            return False
    
    def restore_config(self, backup_file: str = "git_config_backup.txt") -> bool:
        try:
            if not os.path.exists(backup_file):
                return False
            
            with open(backup_file, 'r', encoding='utf-8') as f:
                for line in f:
                    if '=' in line:
                        key, value = line.strip().split('=', 1)
                        subprocess.run(['git', 'config', '--global', key, value], check=True)
            return True
        except Exception as e:
            print(f"恢复配置失败: {e}")
            return False
    
    def test_git_connection(self, repo_url: str = None) -> bool:
        try:
            if repo_url:
                result = subprocess.run(['git', 'ls-remote', repo_url], 
                                      capture_output=True, text=True, timeout=10)
                return result.returncode == 0
            else:
                result = subprocess.run(['git', '--version'], 
                                      capture_output=True, text=True, check=True)
                return True
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            return False
    
    def is_git_repo(self, path: str = ".") -> bool:
        try:
            original_cwd = os.getcwd()
            os.chdir(path)
            
            result = subprocess.run(['git', 'rev-parse', '--git-dir'], 
                                  capture_output=True, text=True)
            
            os.chdir(original_cwd)
            return result.returncode == 0
        except (subprocess.CalledProcessError, OSError):
            return False